#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <pthread.h>

#include "bitmap.h"

#define max(a, b) ((a)>(b))?(a):(b)
#define min(a, b) ((a)>(b))?(b):(a)

// Kernels for edge and blur filters
double Edge[] =
{
	 0, -1,  0,
	-1,  4, -1,
	 0, -1,  0
};

double Blur[] =
{
	0.0, 0.2,  0.0,
	0.2, 0.2,  0.2,
	0.0, 0.2,  0.0
};

const int filterWidth = 3;
const int filterHeight = 3;


const int imageWidth = 240;
const int imageHeight = 320;

//
pixel_t* sourceImage;
pixel_t* frameBuffer;
pixel_t* referenceImage;

int main(int argc, char** argv) {
	int diffcount = 0;
	int max_diff_r = 0;	
	int max_diff_g = 0;	
	int max_diff_b = 0;	
	sourceImage = (pixel_t*) malloc(imageWidth * imageHeight * sizeof(pixel_t));
	frameBuffer = (pixel_t*) malloc(imageWidth * imageHeight * sizeof(pixel_t));
	referenceImage = (pixel_t*) malloc(imageWidth * imageHeight * sizeof(pixel_t));
	// Load the source image from file

	if (!LoadBitmapFile(argv[1], sourceImage, imageWidth, imageHeight)) {
		return -1;
	}
	if(!LoadBitmapFile(argv[2], referenceImage, imageWidth, imageHeight)) {
		return -1;
	}
	// Start worker threads
	int i;
	int j;
	
	for (i = 0; i < imageHeight; i++) {
		for (j=0; j < imageWidth; j++){
			int diff_r = abs(sourceImage[i*imageWidth + j].R - referenceImage[i*imageWidth + j].R);
			int diff_g = abs(sourceImage[i*imageWidth + j].G - referenceImage[i*imageWidth + j].G);
			int diff_b = abs(sourceImage[i*imageWidth + j].B - referenceImage[i*imageWidth + j].B);
			if(diff_r){
				printf("Pixel value R is: %d\n", sourceImage[i*imageWidth + j].R);
			}			
			if(diff_g){
				printf("Pixel value G is: %d\n", sourceImage[i*imageWidth + j].G);
			}
			if(diff_b){
				printf("Pixel value B is: %d\n", sourceImage[i*imageWidth + j].B);
			}
			max_diff_r = (diff_r > max_diff_r) ? diff_r : max_diff_r;
			max_diff_g = (diff_g > max_diff_g) ? diff_g : max_diff_g;
			max_diff_b = (diff_b > max_diff_b) ? diff_b : max_diff_b;
			
			frameBuffer[i*imageWidth + j].R = diff_r ? 255 : 0 ;
			frameBuffer[i*imageWidth + j].G = diff_g ? 255 : 0;
			frameBuffer[i*imageWidth + j].B = diff_b ? 255 : 0;
			diffcount += frameBuffer[i*imageWidth + j].R + frameBuffer[i*imageWidth + j].G + frameBuffer[i*imageWidth + j].B;
				
		}
	}
	
	// Write the output image to file
	if (!WriteBitmapFile(argv[3], frameBuffer, imageWidth, imageHeight)) {
		return -1;
	}
	printf("Diffcount = %d\n", diffcount);
	printf("Max R = %d\n", max_diff_r);
	printf("Max G = %d\n", max_diff_g);
	printf("Max B = %d\n", max_diff_b);
	free(sourceImage);
	free(frameBuffer);
	free(referenceImage);
	return 0;
}
